<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>


    <input type="file" name="img">
    <img src="" class="">
    <button>上传</button>

</body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.1.0/jquery.js"></script>
<script>
    $(`button`).click(function() {
        console.log(11111);
        if (!$(`input`)[0].files[0]) {
            alert("请添加文件")
            return
        }
        var formdata = new FormData();
        formdata.append('img', $(`input`)[0].files[0])
        console.log($(`input`)[0].files[0]);
        $.ajax({
            url: `/upload`,
            type: `post`,
            data: formdata,
            processData: false,
            contentType: false,
            success: function(res) {
                console.log(res);
            }
        })

    })


    //必须在from表单里提交  表单的 enctype格式必须为multipart/form-data 传送方式必须为post
    // let imgfile = document.querySelector(` input[type = file]`)
    // let img = document.querySelector(`img`)
    // console.log(img)
    // let reader = new FileReader()
    // console.log(reader.result);
    // imgfile.onchange = function() {
    //     if (reader.result) return
    //读取files[0]的内容 并转换未base64位的编码  可以用于传输数据
    //     reader.readAsDataURL(this.files[0])
    //     reader.onload = function() {
    //         console.log(11111)
    //         img.src = this.result

    //     }
    // }

    // const submit = document.querySelector(`.submit `)
    // console.log(submit);
    // submit.onclick = function() {
    //     location.reload()
    //     files[0] = {}
    // }
</script>

</html>